#ifndef ZMQ_PUBLIC_H
#define ZMQ_PUBLIC_H

#include <zmq.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>

#include <time.h>

#include "message.h"

static int s_send (void *socket, void *message, unsigned int len) {
    int rc;
    zmq_msg_t zmq_msg;
    zmq_msg_init_size (&zmq_msg, len);
    memcpy (zmq_msg_data (&zmq_msg), message, len);
    rc = zmq_send (socket, &zmq_msg, 0);
    zmq_msg_close (&zmq_msg);
    return (rc);
}

static char * s_recv (void *socket) {
    zmq_msg_t message;
    zmq_msg_init (&message);
    if (zmq_recv (socket, &message, 0))
        return (NULL);
    int size = zmq_msg_size (&message);
    char *string = malloc (size + 1);
    memcpy (string, zmq_msg_data (&message), size);
    zmq_msg_close (&message);
    string [size] = 0;
    return (string);
}


//  Sends string as 0MQ string, as multipart non-terminal
static int s_sendmore (void *socket, void *message, unsigned int len) {
    int rc;
    zmq_msg_t zmq_msg;
    zmq_msg_init_size (&zmq_msg, len);
    memcpy (zmq_msg_data (&zmq_msg), message, len); 
    rc = zmq_send (socket, &zmq_msg, ZMQ_SNDMORE);
    zmq_msg_close (&zmq_msg);
    return (rc);
}

static void s_dump (void *socket)
{
    puts ("----------------------------------------");
    while (1) {
        //  Process all parts of the message
        zmq_msg_t message;
        zmq_msg_init (&message);
        zmq_recv (socket, &message, 0);

        //  Dump the message as text or binary
        char *data = zmq_msg_data (&message);
        int size = zmq_msg_size (&message);
        int is_text = 1;
        int char_nbr;
        for (char_nbr = 0; char_nbr < size; char_nbr++)
            if ((unsigned char) data [char_nbr] < 32
            ||  (unsigned char) data [char_nbr] > 127)
                is_text = 0;

        printf ("[%03d] ", size);
        for (char_nbr = 0; char_nbr < size; char_nbr++) {
            if (is_text)
                printf ("%x", data [char_nbr]);
            else
                printf ("%02X", (unsigned char) data [char_nbr]);
        }
        printf ("\n");

        int64_t more;           //  Multipart detection
        size_t more_size = sizeof (more);
        zmq_getsockopt (socket, ZMQ_RCVMORE, &more, &more_size);
        zmq_msg_close (&message);
        if (!more)
            break;      //  Last message part
    }
}


#endif // ZMQ_PUBLIC_H ///~
